/*
 * @Author: 2112778581 2112778581@qq.com
 * @Date: 2023-10-16 17:41:54
 * @LastEditors: fengshan525 2735332396@qq.com
 * @LastEditTime: 2023-11-05 19:36:40
 * @FilePath: \pra\src\uploader\uploader.service.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { ImageTypes } from '@libs/db/models/images_types.model';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
import { Image } from '@libs/db/models/images.model';
import path, { join } from 'path';
import { ConfigService } from '@nestjs/config';
import { formatAgragateCondition, getConfig, hardRemoveFile } from 'utils';

@Injectable()
export class UploaderService {
  constructor(
    @InjectModel('ImageTypes') private readonly imageTypeModel: Model<ImageTypes>,
    @InjectModel('Image') private readonly imageModel: Model<Image>,
    private readonly configService: ConfigService,
  ) { }

  /**
   * @breif: 上传单张图片，categoryCode默认为'all'表示全部
   * @param {any} file
   * @param {*} req
   * @return {*}
   */
  async uploadSingle(file: any, req) {
    try {
      const { categoryCode } = req || {}
      const basrUrl = getConfig().STATIC_HOST
      const url = basrUrl + file.filename
      let body = {
        url,
        filename: file.filename,
        categoryCode,
      }
      const doc = await this.imageModel.create(body)
      await doc.save()
      return url
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        // throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  /**
   * @breif: 批量上传文件
   * @param {*} files
   * @param {*} req 请求参数
   * @return {*}
   */
  async uploadBatch(files, req) {
    try {
      if (Array.isArray(files) && files.length > 0) {
        files.forEach(async (item) => {
          await this.uploadSingle(item, req);
        })
        return 'upload success'
      }
      return 'upload failure'
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  /**
   * @breif: 根据图片名称和分类查找
   * @param {*} body
   * @return data:{rows:[]}
   */
  async find(body) {
    try {
      let categoryCode
      if (!body.categoryCode || body.categoryCode === 'all') {
        categoryCode = { $regex: '' }
      } else {
        categoryCode = body.categoryCode
      }
      const conditionText = formatAgragateCondition([{ filename: { $regex: body.filename ?? '' }, categoryCode }], body.pageNum, body.pageSize)
      const res = await this.imageModel.aggregate(JSON.parse(conditionText))
      return res[0]
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  // 修改图片
  async update(body) {
    try {
      const res = this.imageModel.findByIdAndUpdate(body._id, body);
      return res
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  // 删除图片
  async delImg(id) {
    try {
      const res = await this.imageModel.findByIdAndDelete(id)
      if (!res) {
        throw new HttpException("删除失败，请检查参数", HttpStatus.BAD_REQUEST)
      }
      return '删除成功'
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  /**
   * @breif: 文件硬删除,当删除报错时，会自动抛出异常
   * @param {*} id
   * @return {*}
   */  
  async delFileHard(id) {
    try {
      const imgInfo = await this.imageModel.findById(id);
      await hardRemoveFile(join(__dirname, `../statics/${imgInfo.filename}`), imgInfo.filename);
      const res = await this.imageModel.findByIdAndDelete(id)
      if (!res) {
        throw new HttpException("删除失败，请检查参数", HttpStatus.BAD_REQUEST)
      }
      return '删除成功'
    } catch (e) {
      throw new HttpException(e, HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }

  /**
   * @breif: 新增图片分类
   * @param {*} body name\code
   * @return {*}
   */
  async createCategory(body) {
    try {
      const exist = await this.imageTypeModel.findOne({ code: body.code });
      if (exist) {
        throw new HttpException("该分类已存在，请修改后重试", HttpStatus.BAD_REQUEST)
      }
      const doc = await this.imageTypeModel.create(body);
      await doc.save()
      return '保存成功'
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  // 获取全部图片分类
  async getAllCategory() {
    try {
      return await this.imageTypeModel.find();
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  // 删除图片
  async delCategory(id) {
    try {
      const res = await this.imageTypeModel.findByIdAndDelete(id)
      if (!res) {
        throw new HttpException("失败，请检查参数", HttpStatus.BAD_REQUEST)
      }
      return 'ok'
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  /**
   * @breif: 更新图片分类
   * @param {*} body
   * @return {*}
   */
  async updateCategory(body) {
    try {
      const res = await this.imageTypeModel.findByIdAndUpdate(body._id, body)
      if (!res) {
        throw new HttpException("失败，请检查参数", HttpStatus.BAD_REQUEST)
      }
      return 'ok'
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  /**
   * @breif: 大文件分片上传
   * @return {*}
   */
  async largeFileUpload() {
    try {

    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }
}
